package com.sgb.jicai.view.fragment;

import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.AbsoluteSizeSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.tabs.TabLayout;
import com.sgb.jicai.R;
import com.sgb.jicai.base.JiCaiBaseApi;
import com.sgb.jicai.databinding.FragmentJcMyPriceBinding;
import com.sgb.jicai.entity.JcCountEntity;
import com.sgb.jicai.entity.JcMyPriceListEntity;
import com.sgb.jicai.event.JiCaiEventEntity;
import com.sgb.jicai.view.activity.JiCaiQuotedPriceActivity;
import com.sgb.jicai.view.adapter.JcMyPirceAdapter;
import com.sgb.jicai.viewmodel.CentralizedMining5Model;
import com.sgb.jicai.viewmodel.JiCaiMyPriceModel;
import com.sgb.link.entity.EventConstant;
import com.swgk.core.base.AppLazyFragment;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.CommonDialog;
import com.swgk.core.dialog.RoundCornerDialog;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.recyclerview.decoration.RecyclerCustomDecoration;
import com.swgk.core.util.ClickUtils;
import com.swgk.core.util.DisplayUtil;
import com.swgk.core.xrecyclerview.XRecyclerView;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.util.ArrayList;
import java.util.List;

public class JcMyPriceFragment extends AppLazyFragment {

    private FragmentJcMyPriceBinding binding;
    public static String KEY_TYPE = "type";
    public static String KEY_STATUS = "status";
    //  1.19改版后传递过来的是集采方式：需方发起、企业专项
    private int type;
    //  状态--全部、集采中、集采完成
    private int status;
    private JcMyPirceAdapter jcMyPirceAdapter;
    JiCaiMyPriceModel model;
    private List<String> typeDatas = new ArrayList<>();//Title
    private int page = 1;
    private boolean isLoadMore = false;
    private String keyWords = "";

    //访问列表的固定字段可以传递进来
    public static JcMyPriceFragment newInstance(int type, int status) {
        JcMyPriceFragment fragment = new JcMyPriceFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(KEY_TYPE, type);
        bundle.putInt(KEY_STATUS, status);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_jc_my_price, container, false);
        model = new ViewModelProvider(this).get(JiCaiMyPriceModel.class);
        model.setActivity(JcMyPriceFragment.this);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        type = getArguments().getInt(KEY_TYPE);
        status = getArguments().getInt(KEY_STATUS);
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    protected void onLazyLoad() {
        initTitle();
        initData();
    }

    @Override
    protected void initView() {
        if (jcMyPirceAdapter == null) {
            jcMyPirceAdapter = new JcMyPirceAdapter(getActivity(), null);
        }
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        binding.recyclerView.setLayoutManager(layoutManager);
        binding.recyclerView.addItemDecoration(new RecyclerCustomDecoration(0, 0, 0, getActivity().getResources().getDimension(R.dimen.dp1), getActivity().getResources().getColor(R.color.color_F5F5F5)));
        binding.recyclerView.setLoadingMoreEnabled(true);
        binding.recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                getData();
            }

            @Override
            public void onLoadMore() {
                if (model.hasNext) {
                    isLoadMore = true;
                    page = page + 1;
                    model.getList(status, page, type, keyWords);
                } else {
                    binding.recyclerView.loadMoreComplete();
                }
            }
        });
        binding.recyclerView.setAdapter(jcMyPirceAdapter);
//我的报价详情
        jcMyPirceAdapter.setOnItemClick(new AdapterOnItemClick<JcMyPriceListEntity>() {
            @Override
            public void onItemClick(JcMyPriceListEntity tenderListEntity, int position) {
                if (!ClickUtils.isDoubleClick()) {
                    model.getH5UrlToDetail(tenderListEntity.getNo(), tenderListEntity.getStatus(), tenderListEntity.getGroupbuyType());
                }
            }
        });
        jcMyPirceAdapter.setDeleteListener(new JcMyPirceAdapter.DeleteListerner() {
            //删除
            @Override
            public void delete(JcMyPriceListEntity entity) {
                String msg = "将永久删除该条数，还要继续吗？";
                new CommonDialog(getActivity()).builder().setPositiveButton("确定").setNegativeButton("取消")
                        .setTitle("温馨提示")
                        .setMsg(msg)
                        .setDialogCallBack(new CommonDialog.DialogCallBack() {
                            @Override
                            public void onRightClick() {
                                //删除报价信息接口
                                model.deletePirce(entity.getNo());
                            }
                            @Override
                            public void onLeftClick() {

                            }
                        }).show();
            }

            //退出
            @Override
            public void exit(JcMyPriceListEntity entity) {
                exitOfferDialog(entity.getNo());
            }
            //修改报价
            @Override
            public void priceDetail(JcMyPriceListEntity entity) {
                JiCaiQuotedPriceActivity.start(getContext(), entity.getNo(), "", 2, entity.getGroupbuyType(),"");// 修改报价 使用原生
            }
        });

        binding.recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                 /*
                SCROLL_STATE_IDLE:停止滚动
                SCROLL_STATE_DRAGGING: 用户慢慢拖动
                SCROLL_STATE_SETTLING：惯性滚动
                */
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {//SCROLL_STATE_IDLE:停止滚动

                }
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (layoutManager.findFirstVisibleItemPosition() > 1) {
                    binding.imgBackTop.setVisibility(View.VISIBLE);
                } else {
                    binding.imgBackTop.setVisibility(View.GONE);
                }
            }
        });
        binding.imgBackTop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.recyclerView.scrollToPosition(0);
            }
        });
    }

    private void initTitle() {
        setTypeDatas();
    }

    public void initData() {
        getData();
        getTabNum();
    }

    public void setTypeDatas() {
        binding.tabLayout.addTab(binding.tabLayout.newTab());
        binding.tabLayout.addTab(binding.tabLayout.newTab());
        binding.tabLayout.addTab(binding.tabLayout.newTab());
        binding.tabLayout.setTabMode(TabLayout.MODE_FIXED);
        setTabTitleSize(binding.tabLayout.getTabAt(0), "全部" + " (0)");
        setTabTitleSize(binding.tabLayout.getTabAt(1), "集采中" + " (0)");
        setTabTitleSize(binding.tabLayout.getTabAt(2), "集采完成" + " (0)");

//        for (int i = 0; i < binding.tabLayout.getTabCount(); i++) {
//            TabLayout.Tab tab = binding.tabLayout.getTabAt(i);
//            if (tab != null) {
//                tab.setCustomView(getTab2View(tab.getText()));
//            }
//        }
        binding.tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
//                updateTab2TextView(tab, true);
                //0所有 1 报价中 2 已结束
                status = tab.getPosition();
                getData();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
//                updateTab2TextView(tab, false);
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });
    }

    private void getData() {
        isLoadMore = false;
        page = 1;
        model.getList(status, page, type, keyWords);
    }

    public void showList(List<JcMyPriceListEntity> list) {
        binding.recyclerView.refreshComplete();
        if (isLoadMore) {
            binding.recyclerView.loadMoreComplete();
            if (list.size() > 0) {
                jcMyPirceAdapter.addDatas(list);
            } else {
                binding.recyclerView.setNoMore(true);
                binding.recyclerView.setLoadingMoreEnabled(false);
            }
            binding.recyclerView.setVisibility(View.VISIBLE);
        } else {
            binding.recyclerView.refreshComplete();
            if (list.size() > 0) {
                binding.recyclerView.setVisibility(View.VISIBLE);
                binding.emptyView.setVisibility(View.GONE);
                jcMyPirceAdapter.setDatas(list);
                binding.recyclerView.setLoadingMoreEnabled(true);
                binding.recyclerView.setNoMore(false);
            } else {
                jcMyPirceAdapter.setDatas(null);
                binding.recyclerView.setVisibility(View.GONE);
                binding.emptyView.setVisibility(View.VISIBLE);
                binding.imgBackTop.setVisibility(View.GONE);
            }
        }
        if (jcMyPirceAdapter.getItemCount() >= 3) {
            binding.recyclerView.setNoMore(!model.hasNext);
        } else {
            binding.recyclerView.setLoadingMoreEnabled(model.hasNext);
        }
        getTabNum();
    }

    public void showUrl(String url) {
        JiCaiBaseApi.startWeb(getActivity(), url);
    }

    //退出报价弹窗
    private void exitOfferDialog(String id) {
        View view = View.inflate(getContext(), R.layout.dialog_two_btn, null);
        final RoundCornerDialog roundCornerDialog = new RoundCornerDialog(getContext(), 0, 0, view, R.style.RoundCornerDialog);
        roundCornerDialog.show();
        roundCornerDialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
        TextView tv_message = (TextView) view.findViewById(R.id.tv_message);
        TextView tv_title = view.findViewById(R.id.tv_title);
        TextView tv_logout_confirm = (TextView) view.findViewById(R.id.tv_logout_confirm);
        tv_title.setVisibility(View.VISIBLE);
        TextView tv_logout_cancel = (TextView) view.findViewById(R.id.tv_logout_cancel);
        tv_title.setText("温馨提示");
        tv_message.setText("您确定退出此次报价?");
        //确定
        tv_logout_confirm.setOnClickListener(v -> {
            model.exitMyOffer(id);
            roundCornerDialog.dismiss();
        });

        //取消
        tv_logout_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                roundCornerDialog.dismiss();
            }
        });
    }

    //更新标题数字
    public void getTabNum() {
        model.getMyOfferBuyListCount(type, keyWords);
    }

    public void setTabNum(List<JcCountEntity> numList) {
        if (null == numList || numList.size() == 0) {
            return;
        }
        for (JcCountEntity entity : numList) {
            String num = " (" + (Integer.valueOf(entity.getCount()) > 99 ? "99+" : entity.getCount()) + ")";
            switch (Integer.valueOf(entity.getStatus())) {//012
                case 0:
                    setTabTitleSize(binding.tabLayout.getTabAt(0), "全部" + num);
                    break;
                case 1:
                    setTabTitleSize(binding.tabLayout.getTabAt(1), "集采中" + num);
                    break;
                case 2:
                    setTabTitleSize(binding.tabLayout.getTabAt(2), "集采完成" + num);
                    break;
            }
        }
    }

    private void setTabTitleSize(TabLayout.Tab tab, String text) {
        if (null == tab) {//多个fragment已创建，但是懒加载时后面的页面还没有初始化tab
            return;
        }
        int start = text.indexOf("(");
        int end = text.length();
        SpannableString textSpan = new SpannableString(text);
        try {
            textSpan.setSpan(new AbsoluteSizeSpan(DisplayUtil.sp2px(getActivity(), 14)), 0, start, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
            textSpan.setSpan(new AbsoluteSizeSpan(DisplayUtil.sp2px(getActivity(), 10)), start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
            tab.setText(textSpan);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //删除弹窗
    private void deleteDialog(String id) {
        View view = View.inflate(getContext(), R.layout.dialog_two_btn, null);
        final RoundCornerDialog roundCornerDialog = new RoundCornerDialog(getContext(), 0, 0, view, R.style.RoundCornerDialog);
        roundCornerDialog.show();
        roundCornerDialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
        TextView tv_message = (TextView) view.findViewById(R.id.tv_message);
        TextView tv_title = view.findViewById(R.id.tv_title);
        TextView tv_logout_confirm = (TextView) view.findViewById(R.id.tv_logout_confirm);
        tv_title.setVisibility(View.VISIBLE);
        TextView tv_logout_cancel = (TextView) view.findViewById(R.id.tv_logout_cancel);
        tv_title.setText("温馨提示");
        tv_message.setText("您确定删除此次集采?");

        //确定
        tv_logout_confirm.setOnClickListener(v -> {
            //删除
            model.deleteData(id);
            roundCornerDialog.dismiss();
        });

        //取消
        tv_logout_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                roundCornerDialog.dismiss();
            }
        });
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(JiCaiEventEntity event) {
        if (event.getCode() == EventConstant.EVENT_JICAI_MY_PRICE) {
            keyWords = event.getName();
            getData();
        } else if (event.getCode() == EventConstant.EVENT_WEBVIEW_RELOAD) {
            getData();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
